package com.examples

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity

class ActivityResultFragment : Fragment() {
    var requestCode: Int = -1
    lateinit var intent: Intent
    private var onSuccessListener: ((Intent?) -> Unit?)? = null
    private var onFailureListener: ((Intent?) -> Unit?)? = null

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        startActivityForResult(intent, requestCode)
        Log.d("tag", "startActivityForResult$requestCode")
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
        Log.d("tag", "onActivityResult requestCode=$requestCode,resultCode=$resultCode")
        if (requestCode == this.requestCode) {
            if (resultCode == Activity.RESULT_OK) {
                onSuccessListener?.invoke(data)
            } else {
                onFailureListener?.invoke(data)
            }
            activity?.supportFragmentManager?.beginTransaction()?.remove(this)?.commitAllowingStateLoss()
        }
    }


    fun onSuccess(activity: FragmentActivity, action: (data: Intent?) -> Unit): ActivityResultFragment {
        activity.supportFragmentManager.beginTransaction().add(this, "onActivityResultFragment$requestCode").commitAllowingStateLoss()
        onSuccessListener = action
        return this
    }

    fun onFailure(action: (data: Intent?) -> Unit): ActivityResultFragment {
        onFailureListener = action
        return this
    }

    companion object {
        @JvmStatic
        private var staticRequestCode = 0
            get() {
                ++field
                field = if (field > 65535) 0 else field
                return field
            }


        @JvmOverloads
        @JvmStatic
        fun getInstance(intent: Intent): ActivityResultFragment {
            val activityResultFragment = ActivityResultFragment()
            activityResultFragment.intent = intent
            activityResultFragment.requestCode = staticRequestCode
            return activityResultFragment
        }
    }
}